﻿#批量命名图片
import os,time,re,sys
from datetime import datetime

ROOT_PATH = os.path.abspath('..') #脚步所在的上一层目录
CUR_OPT_PATH = "" #当前操作的根目录
G_OWN_NUMS = []; #当前目录下已经用的数字名称
G_LOGS = ""

print("是否开始重名",ROOT_PATH ,"该目录下的所有图片文件 sys.argv",sys.argv)
answer=input("是y/否n:\n")
if answer!="y":
	exit()
print("是否递归重名",ROOT_PATH ,"该目录下的所有子目录(script目录除外)的图片文件")
loop = input("是y/否n:\n")
isLoop = (loop=="y") #是否递归所有子目录

print("-------------开始重命名-------------")
totalST = time.time()
def joinPath(name):
	name = os.path.join(CUR_OPT_PATH,name)	
	return name

#获取后缀
def getFix(url):
	fix = os.path.splitext(joinPath(url))[1]
	return fix
#获取文件名
def getName(url):
	fname = os.path.splitext(joinPath(url))[0]
	return fname

#获取新的文件名字	
def getNewName(i,fix):
	src = "00000"
	src = src[0:(len(src)-len(str(i)))]+str(i);
	src=joinPath(src+fix) 
	return src

regObj = re.compile(r'\d+$')
def isPureNum(fname):
	ret = regObj.match(fname)	
	return ret and len(fname)==5
	
#获取一个目录下面的所有png和jpg图片
def getDirImgs(curPath):
	allImgs=[x for x in os.listdir(curPath) if os.path.isfile(os.path.join(curPath,x)) and (os.path.splitext(os.path.join(curPath,x))[1]=='.png' or os.path.splitext(os.path.join(curPath,x))[1]=='.jpg') ]
	return allImgs

def getDirs(curPath):
	return [os.path.join(curPath,x) for x in os.listdir(curPath) if os.path.isdir(os.path.join(curPath,x)) and x!="script"]
	
allDirs = [ROOT_PATH]+getDirs(ROOT_PATH)
#筛选目录下的文件名不是纯数字的图片文件
def filterImags(allImgs):
	ownNums = [];
	strFiles = [];
	for fname in allImgs:
		arr = re.split(r'\.',fname)
		if isPureNum(arr[0]):		
			ownNums.append(int(arr[0]))
		else:
			strFiles.append(fname)

	ownNums.sort()
	return ownNums,strFiles
	
def getUnUseNum(i):	
	while i in G_OWN_NUMS:
		i = i+1	
	return i
	

#批量重命名
def batRename(strFiles):
	st = time.time()
	index = 0;
	global G_LOGS;
	logs="目录:"+CUR_OPT_PATH+"\r"
	for fname in strFiles:	
		index = getUnUseNum(index)
		oldn = joinPath(fname)
		newn = getNewName(index,getFix(fname))		
		os.rename(oldn,newn)
		index = index+1
		logs = logs + "文件:"+oldn+";==>被重命名为:"+newn+"\r"
	
	G_LOGS = G_LOGS + logs	
	et = time.time()
	ct = round(et - st,2);
	print("共重命名%s目录下%s个文件,耗时"%(CUR_OPT_PATH,len(strFiles)),ct,"毫秒")
			
#重命名一个目录下的图片文件
def renameDir(d):
	global CUR_OPT_PATH;
	CUR_OPT_PATH = d;
	global G_OWN_NUMS
	allImgs = getDirImgs(d)
	G_OWN_NUMS,strFiles= filterImags(allImgs);
	batRename(strFiles);

def beginRename(isLoop,allDirs):
	if isLoop:
		for d in allDirs:
			renameDir(d)
	else:
		renameDir(ROOT_PATH)

def writeLogs():
	global G_LOGS
	if G_LOGS!="":		
		cururl = os.path.join(os.path.abspath(os.curdir),"logs.txt")
	if os.path.isfile(cururl):
		os.remove(cururl)			
	with open(cururl,'w') as f:
		arr = re.split(r'\.',str(datetime.now()));		
		G_LOGS = G_LOGS+arr[0]
		f.write(G_LOGS)

beginRename(isLoop,allDirs);
writeLogs();
total = time.time()
print("程序总耗时%s"%str(round((total-totalST),2)),"毫秒.")

